import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/playbill/main_feature/main_production.dart';

part 'splash_production.page.dart';

/// 启动页面
@PagePath('/')
class SplashProduction extends StatefulWidget {
  const SplashProduction({super.key});

  @pageRouteQuery
  static const query = _$SplashProductionQuery();

  @override
  State<SplashProduction> createState() => _SplashProductionState();
}

class _SplashProductionState extends State<SplashProduction> {
  @override
  void initState() {
    super.initState();
    // 等待首帧渲染完成后再访问InheritedWidget
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeAndNavigate();
    });
  }

  /// 初始化所有状态管理并跳转到主页
  void _initializeAndNavigate() async {
    // 获取全局状态管理实例
    final globalState = GlobalStateProvider.of(context);

    // 初始化用户数据
    globalState.userRoom.initializeDefaultUsers();

    // 初始化打卡数据
    globalState.checkInRoom.initializeDefaultCheckIns();

    // 初始化关注数据
    globalState.followRoom.initializeDefaultFollows();

    // 初始化湖泊推荐数据
    globalState.lakeRecommendRoom.initializeDefaultLakeRecommends();

    // 初始化动态数据
    globalState.dynamicRoom.initializeDefaultDynamics();

    // 初始化徽章数据
    globalState.badgeRoom.initializeDefaultBadges();

    // 初始化群聊数据
    globalState.groupChatRoom.initializeDefaultGroupChats();

    // 初始化单聊数据
    globalState.singleChatRoom.initializeDefaultSingleChats();

    // 初始化答题数据
    globalState.quizRoom.initializeDefaultQuizQuestions();

    // 等待3秒后跳转到主页
    await Future.delayed(const Duration(seconds: 3));
    if (mounted) {
      context.router.push(MainProduction.query());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.splashBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Logo图片
            Container(
              width: 99.w,
              height: 99.w,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(AssetManifest.logo),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(32.r),
                border: Border.all(color: ColorPalette.white, width: 5.w),
              ),
            ),
            8.h.heightBox,

            Text('Thal')
                .carterOne(
                  weight: FontWeight.w400,
                  shadows: [
                    Shadow(
                      offset: Offset(1, 2),
                      blurRadius: 0,
                      color: ColorPalette.blue1,
                    ),
                  ],
                )
                .fontSize(30.sp)
                .textColor(ColorPalette.white),

            32.h.heightBox,

            // 加载动画
            _CustomLoader(),
          ],
        ),
      ),
    );
  }
}

/// 加载动画组件
class _CustomLoader extends StatefulWidget {
  @override
  _CustomLoaderState createState() => _CustomLoaderState();
}

class _CustomLoaderState extends State<_CustomLoader>
    with TickerProviderStateMixin {
  late AnimationController _rotationController;
  late AnimationController _pulseController;
  late AnimationController _fadeController;

  @override
  void initState() {
    super.initState();

    // 旋转动画控制器
    _rotationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();

    // 脉冲动画控制器
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    )..repeat(reverse: true);

    // 淡入淡出动画控制器
    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _rotationController.dispose();
    _pulseController.dispose();
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: Listenable.merge([
        _rotationController,
        _pulseController,
        _fadeController,
      ]),
      builder: (context, child) {
        return Transform.rotate(
          angle: _rotationController.value * 2 * 3.14159,
          child: ScaleTransition(
            scale: Tween<double>(begin: 0.9, end: 1.1).animate(
              CurvedAnimation(
                parent: _pulseController,
                curve: Curves.easeInOut,
              ),
            ),
            child: FadeTransition(
              opacity: Tween<double>(begin: 0.7, end: 1.0).animate(
                CurvedAnimation(
                  parent: _fadeController,
                  curve: Curves.easeInOut,
                ),
              ),
              child: Container(
                width: 50.w,
                height: 50.h,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: RadialGradient(
                    colors: [
                      ColorPalette.blue1,
                      ColorPalette.blue2,
                      ColorPalette.blue3,
                    ],
                    stops: [0.0, 0.6, 1.0],
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: ColorPalette.blue1.withOpacity(0.4),
                      blurRadius: 15,
                      spreadRadius: 2,
                    ),
                  ],
                ),
                child: Center(
                  child: Container(
                    width: 35.w,
                    height: 35.h,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: ColorPalette.white,
                    ),
                    child: Center(
                      child: Container(
                        width: 25.w,
                        height: 25.h,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          gradient: LinearGradient(
                            colors: [ColorPalette.blue1, ColorPalette.blue2],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                        ),
                        child: Center(
                          child: Container(
                            width: 15.w,
                            height: 15.h,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: ColorPalette.white,
                            ),
                            child: Center(
                              child: Container(
                                width: 8.w,
                                height: 8.h,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: ColorPalette.blue1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
